package com.lottery.ruok.lottrey.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.applozic.mobicomkit.ChatConfig;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.GetPacketResultActivity;
import com.lottery.ruok.lottrey.activity.GiveRewardActivity;
import com.lottery.ruok.lottrey.activity.GiveRewardDetailActivity;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.chat.RongCloudChatManager;
import com.lottery.ruok.lottrey.chat.event.handler.OnConversationClickListener;
import com.lottery.ruok.lottrey.chat.model.prize.message.PrizeMessage;
import com.lottery.ruok.lottrey.chat.model.redpacket.message.receiveRedPacketMessage.ReceiveRedPacketMessage;
import com.lottery.ruok.lottrey.chat.model.redpacket.message.sendRedPacketMessage.RedPacketMessage;
import com.lottery.ruok.lottrey.chat.utils.ChatUtils;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.dialog.RedPacketAniDialog;
import com.lottery.ruok.lottrey.eventbusObject.GrabRedPacketSucess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GrabGiftRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GrabGiftResponse;
import com.lottery.ruok.lottrey.utils.ClickUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Iterator;

import io.rong.imkit.RongIM;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import utils.StringUtils;
import utils.Utils;

/**
 * 作者：lm
 * <p>
 * 创建日期：2018/9/13$
 * <p>
 * 描述：
 */
public class MyConversationClickListener implements RongIM.ConversationClickListener {
    private boolean click=false;

    /**
     * 当点击用户头像后执行。
     *
     * @param context          上下文。
     * @param conversationType 会话类型。
     * @param user             被点击的用户的信息。
     * @param targetId         会话 id
     * @return 如果用户自己处理了点击后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
     */
    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
        switch (conversationType) {
            case CHATROOM:
                if (TextUtils.isEmpty(com.lottery.ruok.lottrey.userInfo.UserInfo.getToken())) {
                    Utils.showToast("未登录,不能打赏");
                }else if (com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTest() == 1 && com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTry() != 1) {
                    Utils.showToast(Common.IS_TEST);
                }else{
                    if (!ChatUtils.isMySelf(user.getName())) {
                        //大赏
                        sendPrize(context, conversationType, user, targetId);
                        return true;
                    }
                }
                break;
            case PRIVATE:
                if (TextUtils.isEmpty(com.lottery.ruok.lottrey.userInfo.UserInfo.getToken())) {
                    Utils.showToast("未登录,不能打赏");
                }else if (com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTest() == 1 && com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTry() != 1) {
                    Utils.showToast(Common.IS_TEST);
                }else{
                    if (!ChatUtils.isMySelf(user.getName())) {
                        //大赏
                        sendPrize(context, conversationType, user, targetId);
                        return true;
                    }
                }
                break;
        }
        return true;
    }

    /**
     * 当长按用户头像后执行。
     *
     * @param context          上下文。
     * @param conversationType 会话类型。
     * @param user             被点击的用户的信息。
     * @param targetId         会话 id
     * @return 如果用户自己处理了点击后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
     */
    @Override
    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
        return false;
    }

    /**
     * 当点击消息时执行。
     *
     * @param context 上下文。
     * @param view    触发点击的 View。
     * @param message 被点击的消息的实体信息。
     * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
     */
    @Override
    public boolean onMessageClick(Context context, View view, Message message) {
        if (message.getObjectName().equals("RCD:SendRPMsg")) {
            if (!click) {
                click=true;
                if (!com.lottery.ruok.lottrey.userInfo.UserInfo.getToken().equals("")) {

               /* if (message.getConversationType().getName().equals("chatroom")){
                    RedPacketMessage content= (RedPacketMessage) message.getContent();
                    setJump(context,content,message);
                }else if (message.getConversationType().getName().equals("private")){

                }*/
                    RedPacketMessage content = (RedPacketMessage) message.getContent();
                    setJump(context, content, message);

                } else {
                    click=false;
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                    ((Activity) context).overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                }
            }

        } else if (message.getObjectName().equals("RCD:RwrdMsg")) {
            PrizeMessage content = (PrizeMessage) message.getContent();
            GiveRewardDetailActivity.startActivity(context, content);
        }

        return false;
    }

    /**
     * 当点击链接消息时执行。
     *
     * @param context 上下文。
     * @param link    被点击的链接。
     * @param message 被点击的消息的实体信息
     * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
     */
    @Override
    public boolean onMessageLinkClick(Context context, String link, Message message) {
        return false;
    }

    /**
     * 当长按消息时执行。
     *
     * @param context 上下文。
     * @param view    触发点击的 View。
     * @param message 被长按的消息的实体信息。
     * @return 如果用户自己处理了长按后的逻辑处理，则返回 true，否则返回 false，false 走融云默认处理方式。
     */
    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        return false;
    }

    /**
     * 大赏
     *
     * @param context
     * @param conversationType
     * @param user
     * @param targetId
     */
    private void sendPrize(Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) {
        Intent intent = new Intent(context, GiveRewardActivity.class);
        intent.putExtra(GiveRewardActivity.EXTRA_CONVERSATION_TYPE, conversationType.getName());
        intent.putExtra(GiveRewardActivity.EXTRA_USER, user);
        intent.putExtra(GiveRewardActivity.EXTRA_TARGET_ID, targetId);
        context.startActivity(intent);

    }

    private void setJump(final Context context, final RedPacketMessage content, final Message message) {
        if (com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTest() == 1 && com.lottery.ruok.lottrey.userInfo.UserInfo.getIsTry() != 1) {
            // utils.Utils.showToast(Common.IS_TEST);
            Toast.makeText(context.getApplicationContext(), Common.IS_TEST, Toast.LENGTH_SHORT).show();
            click=false;
        } else {
            RetrofitBase.getRetrofit().create(GrabGiftRequest.class).getResult(content.getMsgId() + "", com.lottery.ruok.lottrey.userInfo.UserInfo.getUsername(), com.lottery.ruok.lottrey.userInfo.UserInfo.getToken())
                    .compose(RxHelper.<GrabGiftResponse>handleResult())
                    .subscribe(new RxSubscribe<GrabGiftResponse>(context.getApplicationContext()) {
                        @Override
                        protected void _onNext(GrabGiftResponse grabGiftResponse) {
                            click=false;
                            switch (grabGiftResponse.getTypes()) {
                                case 0:
                                    // utils.Utils.showToast(grabGiftResponse.getMsg());
                                    Toast.makeText(context.getApplicationContext(), "红包已过期", Toast.LENGTH_SHORT).show();
                                    break;
                                case 1: {
                                    //播放动画，再跳转到红包领取详情页
                                    // utils.Utils.showToast(grabGiftResponse.getMsg());
                                    Toast.makeText(context.getApplicationContext(), grabGiftResponse.getMsg(), Toast.LENGTH_SHORT).show();
                                    GrabRedPacketSucess grabRedPacketSucess = new GrabRedPacketSucess();
                                    grabRedPacketSucess.setRedPacketFrom(content.getSendUserId());
                                    grabRedPacketSucess.setHave_get_packet_id(grabGiftResponse.getGift_rand_id());
                                    grabRedPacketSucess.setRedPacketID(grabGiftResponse.getGift_id());
                                    grabRedPacketSucess.setConversationId(message.getTargetId());
                                    EventBus.getDefault().post(grabRedPacketSucess);
                                    //发送抢红包消息
                                    ReceiveRedPacketMessage receiveRedPacketMessage = new ReceiveRedPacketMessage();
                                    receiveRedPacketMessage.setMsgId(StringUtils.parseLong(grabGiftResponse.getGift_id()));
                                    receiveRedPacketMessage.setChildId(StringUtils.parseLong(grabGiftResponse.getGift_rand_id()));
                                    receiveRedPacketMessage.setDate(System.currentTimeMillis() + "");
                                    receiveRedPacketMessage.setMoney(StringUtils.parseDouble(grabGiftResponse.getAmount()));
                                    receiveRedPacketMessage.setReceiveUserId(com.lottery.ruok.lottrey.userInfo.UserInfo.getMyUserId());
                                    receiveRedPacketMessage.setSendUserId(content.getSendUserId());

                                    receiveRedPacketMessage.setReceiveUserNickname(com.lottery.ruok.lottrey.userInfo.UserInfo.getNickname());
                                    receiveRedPacketMessage.setReceiveUserAvatar(com.lottery.ruok.lottrey.userInfo.UserInfo.getAvatar());
                                    UserInfo sendUser = RongUserInfoManager.getInstance().getUserInfo(content.getSendUserId());
                                    if (sendUser != null) {
                                        receiveRedPacketMessage.setSendUserNickname(sendUser.getName());
                                        receiveRedPacketMessage.setSendUserAvatar(sendUser.getPortraitUri().toString());
                                    } else {
                                        receiveRedPacketMessage.setSendUserNickname(content.getSendUserNickname());
                                    }

                                    receiveRedPacketMessage.setType(content.getType());
                                    receiveRedPacketMessage.setTargetId( com.lottery.ruok.lottrey.userInfo.UserInfo.getRoomId());
                                    String messageType = message.getConversationType().getName();
                                    if (messageType.equals("private")) {
                                        RongCloudChatManager.sendMessagePrivate(content.getSendUserId(), receiveRedPacketMessage);
                                    } else if (messageType.equals("chatroom")) {
                                        RongCloudChatManager.sendMessage( com.lottery.ruok.lottrey.userInfo.UserInfo.getRoomId(), receiveRedPacketMessage);
                                    }


                                    Intent intent = new Intent(context, RedPacketAniDialog.class);
                                    intent.putExtra(ChatConfig.PACKET_GET_ID, grabGiftResponse.getGift_rand_id());
                                    intent.putExtra(ChatConfig.PACKET_ID, grabGiftResponse.getGift_id());
                                    intent.putExtra(ChatConfig.CONVERSATION_ID, message.getTargetId());
                                    context.startActivity(intent);
                                    break;
                                }
                                case 2: {
                                    //跳转到红包领取详情页
                                    //utils.Utils.showToast(grabGiftResponse.getMsg());
                                    Toast.makeText(context.getApplicationContext().getApplicationContext(), grabGiftResponse.getMsg(), Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(context, GetPacketResultActivity.class);
                                    intent.putExtra(ChatConfig.PACKET_GET_ID, grabGiftResponse.getGift_rand_id());
                                    intent.putExtra(ChatConfig.PACKET_ID, grabGiftResponse.getGift_id());
                                    context.startActivity(intent);
                                    break;
                                }
                                case 3:
                                    //  utils.Utils.showToast(grabGiftResponse.getMsg());
                                    Toast.makeText(context.getApplicationContext(), "来晚了,红包已被领完", Toast.LENGTH_SHORT).show();
                                    break;
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            click=false;
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        }
    }


}
